package Filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

@WebFilter("/ceshi/*")
public class FilterTest1 implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("过滤器来了！初始化操作");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("客户端又发出请求了");
        //1不需要登录和注册的页面直接放行， login.jsp html
        //filterChain.doFilter(servletRequest,servletResponse)
        //2成功登录的放行
        //filterChain,doFilter(servletRequest,servletResponse)
        //3没有session的值拦截，则直接跳到login
        //放行
        servletRequest.setCharacterEncoding("utf-8");
        servletResponse.setContentType("text/html;charset=utf-8");

        HttpSession session = ((HttpServletRequest) servletRequest).getSession(false);
        String requestURI = ((HttpServletRequest) servletRequest).getRequestURI();
        if (requestURI.endsWith("/web.jsp")||requestURI.endsWith("/usererror")||
                requestURI.endsWith("/code")||requestURI.endsWith("/islogin")){

            filterChain.doFilter(servletRequest,servletResponse);
        }else  if (session==null || session.getAttribute("user")==null){
            PrintWriter writer = servletResponse.getWriter();
            writer.write("<script> " +
                    "alert('请正常登录');" +
                    "window.location.href='web.jsp'" +
                    "</script>");

        }else if (session !=null && session.getAttribute("user")!=null){
            filterChain.doFilter(servletRequest,servletResponse);
        }
    }

    @Override
    public void destroy() {
        System.out.println("过滤期结束了");
    }
}
